﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using My.Core.Enums;
using My.Core.Model;
using NLog;

namespace My.Core.Filters
{
	/// <summary>
	/// 模型验证过滤
	/// </summary>
	public class DataValidationFilter : ActionFilterAttribute
	{
		static readonly Logger logger = LogManager.GetCurrentClassLogger();

		/// <summary>
		/// Action请求前，自定义 请求参数判断 异常返回
		/// </summary>
		/// <param name="context"></param>
		/// <param name="next"></param>
		/// <returns></returns>
		public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
		{
			ApiResult response = new ApiResult();
			response.code = (int)ResultCode.PARAM_ERROR;

			var values = context.ModelState.Values;
			foreach (var item in values)
			{
				foreach (var err in item.Errors)
				{
					if (err.ErrorMessage.Contains("JSON"))
					{
						return next();
					}
					if (!string.IsNullOrEmpty(response.message))
					{
						response.message += " | ";
					}

					response.message += err.ErrorMessage;
				}
			}
			if (!string.IsNullOrEmpty(response.message))
			{
				logger.Info($"请求参数错误,{response.message}");
				context.Result = new JsonResult(response);
			}
			return base.OnActionExecutionAsync(context, next);
		}
	}
}
